/*=============================================================================
#    The element-comm is a tentative program used to test our ideas.           
#                       Copyright (C)  bgao                                    
#
#     This program is free software; you can redistribute it and/or            
#      modify it under the terms of the GNU General Public License             
#     as published by the Free Software Foundation; either version 2           
#         of the License, or (at your option) any later version.               
#
#     This program is distributed in the hope that it will be useful,          
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            
#             GNU General Public License for more details.                    
#
#    You should have received a copy of the GNU General Public License        
#     along with this program; if not, write to the Free Software             
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,             
#                       MA  02110-1301, USA.                                  
#==============================================================================
# $Id: buf.c 348 2010-11-29 09:01:16Z bgao $ 
#
# $Author: bgao $ 
#
# $Revision: 348 $ 
#
# $Date: 2010-11-29 17:01:16 +0800 (星期一, 29 十一月 2010) $ 
#
# Description: 
#
=============================================================================*/
/*! @file buf.c
 *  @brief This is a implementation of buffer structure.
 */
#include <string.h>
#include "buf.h"

/*! define a list of buf */
MEM(buf_list);

/*! global buf storage */
buf_t buf_pool[BUF_SIZE];

/*! initialize the buf structure.
 *  @return return -1 if error occurs else return 0.
 */
int8 buf_init(void)
{
    int r, t;
    pool_t p;

    p.ptr = buf_pool;
    p.num = BUF_SIZE;
    p.size = sizeof(buf_t);

    memset(buf_pool, 0, sizeof(buf_pool));
    t = mem_init(buf_list, &p);

    if (r == MAC_ERR || t == MAC_ERR)
        return MAC_ERR;
    else
        return MAC_OK;
}

/*! allocate a block of buf from the buf pool.
 *  @param is_trx bool flag indicate whether the buffer is used to
 *         receive/transmit frame.
 *  @return pointer to the block being allocated.
 *          NULL if the buf is empty.
 */
buf_t *buf_alloc(bool is_trx)
{
    buf_t *m;

    m = mem_alloc(buf_list);
    if (m == NULL) {
        return NULL;
    }

    m->length = 0;
    memset(m->array, 0, 128);
    m->ptr = (is_trx)? &m->array[127] : &m->array[0];

    return m;
}

/*! free a block of buf to the buf pool.
 *  @param buf pointer to the block to be freed.
 *  @return -1 if error occurs else return 0.
 */
int8 buf_free(buf_t *buf)
{
    int8 r;
    if (buf == NULL) {
        return MAC_ERR;
    }
    r = mem_free(buf_list, buf);
    return r;
}

